var needle = require('needle');
var WechatAPI = require('wechat-api');
var payUtil = require('./payUtil');
var wxpay = require('./wxpay.json');
var options = {
    headers:{
        'Content-Type':'application/json'
    }
}
/**
 * 增加白名单
 * @param openid
 * @param usernames
 * @param callback
 */
exports.addWhiteList = function(acctoken, openids, usernames, callback){
    var url = 'https://api.weixin.qq.com/card/testwhitelist/set?access_token='+acctoken;
    var postdata = {
        openid: openids,
        username: usernames
    }
    needle.post(url, JSON.stringify(postdata), options, function(err, resp, body){
        callback(err, body)
    });
}
/**
 * 起调卡券列表唯一性信息
 * @param cardId
 * @param cardType
 * @returns {{appsecret: *, app_id: *, location_id: string, time_stamp: number, nonce_str: *, card_id: (*|string), card_type: (*|string)}}
 */
exports.chooseCardParam = function(cardId, cardType){
    var params = {
        appsecret: wxpay.key_secret,
        app_id: wxpay.appid,
        location_id: '',
        time_stamp: payUtil.generateTimeStamp()+'',
        nonce_str: payUtil.generateNonce(32),
        card_id: cardId || '',
        card_type: cardType || ''
    }
    var sorted = payUtil.ksort(params);
    var tempStr = '';
    for(key in sorted){
        tempStr += sorted[key];
    }
    var sign = payUtil.sha1(tempStr);
    params.appsecret = '';
    params.sign_type = 'sha1';
    params.card_sign = sign;
    return params
}

/**
 *  获得卡券唯一性信息
 * @param card {
 *      appsecret, card_id, timestamp, code, openid, balance
 * }
 * @param callback
 */
exports.getCardParam = function(card){
    card.timestamp = payUtil.generateTimeStamp()+'';
    card.appsecret = wxpay.key_secret;
    var arr = [];
    for(key in card){
        arr.push(card[key]);
    }
    var sorted = arr.sort();
    var tempStr = '';
    for(key in sorted){
        tempStr += sorted[key];
    }
    console.log(tempStr)
    var sign = payUtil.sha1(tempStr);
    var ext = {
        code: card.code || '',
        openid: card.openid || '',
        timestamp: card.timestamp,
        signature: sign
    }
    return {
        card_id: card.card_id,
        card_ext: ext
    }
}